package realestate.manager.owner;


import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by IntelliJ IDEA.
 * User: Admin
 * Date: 19.04.11
 * Time: 15:11
 * To change this template use File | Settings | File Templates.
 */
@Remote(value = IRAOwner.class)
@Stateless(name = "OwnerOwnerManager")
public class RAOwner implements IRAOwner {

	@PersistenceContext(name = "RealEstate")
	private EntityManager em;

	@Override
	public Owner addOwner(Owner new_owner) {
		String owner_key = generateKeyForOwner(new_owner);
		new_owner.setKey(owner_key);
		em.persist(new_owner);
		em.flush();
		return new_owner;
	}

	private String  generateKeyForOwner(Owner owner) {
		MessageDigest digest = null;
		String result_string = "";
		try {
			digest = MessageDigest.getInstance("SHA-1");
			byte[] result = digest.digest(owner.getOwnerEMail().getBytes());
			BigInteger big_int = new BigInteger(1, result);
			result_string = big_int.toString(16);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();

		} finally {
			return result_string;
		}
	}

	@Override
	public boolean removeOwner(Owner owner_to_remove) {
		Owner persisted_owner = getOwnerById(owner_to_remove.getId());
		if(persisted_owner == null)
			return false;
		em.remove(persisted_owner);
		em.flush();
		return true;
	}

	@Override
	public Owner getOwnerById(Long owner_id) {
		return em.find(Owner.class, owner_id);
	}

	@Override
	public Owner getOwnerByEMail(String owner_e_mail_string) {
		Query get_owner_query = em.createNamedQuery(Owner.OWNER_BY_E_MAIL);
		get_owner_query.setParameter((int) 1, owner_e_mail_string);
		return (Owner) get_owner_query.getSingleResult();
	}

	@Override
	public Owner getOwnerByKey(String owner_key) {
		Query get_owner_query = em.createNamedQuery(Owner.OWNER_BY_KEY);
		get_owner_query.setParameter((int)1,owner_key);
		return (Owner) get_owner_query.getSingleResult();
	}
}
